package com.zzyl.serve.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.dto.DeviceDataPageReqDto;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.service.IDeviceService;
import com.zzyl.serve.vo.IotMsgBody;
import com.zzyl.serve.vo.IotMsgHeader;
import com.zzyl.serve.vo.IotMsgNotifyData;
import com.zzyl.serve.vo.IotMsgService;
import io.swagger.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceDataMapper;
import com.zzyl.serve.domain.DeviceData;
import com.zzyl.serve.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备数据Service业务层处理
 * 
 * @author qyy
 * @date 2025-08-23
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }

    @Override
    public TableDataInfo<DeviceData> listPage(DeviceDataPageReqDto dto) {
        //数据库中获取数据
        LambdaQueryWrapper<DeviceData> wrapper = Wrappers.<DeviceData>lambdaQuery()
                .like(StringUtils.isNotEmpty(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .like(StringUtils.isNotEmpty(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .between(dto.getStartTime() != null && dto.getEndTime() != null, DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime());

        Page<DeviceData> page = page(new Page<>(dto.getPageNum(), dto.getPageSize()),wrapper);
        //返回数据给客户端
        TableDataInfo<DeviceData> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        return tableDataInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatchData(String content) {
        //需要批量保存数据到数据库中
        if(content == null){
            return;
        }
        //转换数据格式获取数据，健壮性判断
        JSONObject jsonObject = JSONUtil.parseObj(content);
        JSONObject notifyData = jsonObject.getJSONObject("notify_data");
        if(notifyData==null){
            return;
        }
        IotMsgNotifyData iotMsgNotifyData = JSONUtil.toBean(notifyData, IotMsgNotifyData.class);
        IotMsgBody body = iotMsgNotifyData.getBody();
        //头部中存储了deviceId
        IotMsgHeader header = iotMsgNotifyData.getHeader();
        if(body==null || ObjUtil.isEmpty(body.getServices())){
            return;
        }
        IotMsgService iotMsgService = body.getServices().get(0);

        //封装数据保存到数据库中
            //从消息队列中获取数据
        String timeStr = iotMsgService.getEventTime();
        LocalDateTime time0 = LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));
        LocalDateTime eventTime = time0.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        Map<String, Object> properties = iotMsgService.getProperties();
            //从device表中获取数据
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getIotId, header.getDeviceId());
        Device device = deviceService.getOne(wrapper);
            //封装
        List<DeviceData> list = new ArrayList<>();
        properties.forEach((prop,value)->{
            DeviceData deviceData = new DeviceData();
            deviceData.setDeviceName(device.getDeviceName());
            deviceData.setIotId(header.getDeviceId());
            deviceData.setProductKey(device.getProductKey());
            deviceData.setProductName(device.getProductName());
            deviceData.setFunctionId(prop);
            deviceData.setAccessLocation(device.getBindingLocation());
            deviceData.setLocationType(device.getLocationType());
            deviceData.setPhysicalLocationType(device.getPhysicalLocationType());
            deviceData.setDeviceDescription(device.getDeviceDescription());
            deviceData.setDataValue(value+"");
            deviceData.setAlarmTime(eventTime);
            list.add(deviceData);
        });

        saveBatch(list);
        //将数据缓存到redis中
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,device.getIotId(),JSONUtil.toJsonStr(list));
    }


}
